const Service = require('egg').Service;

class UserService extends Service {
    async getList() {
        const { ctx, app } = this;
        const titles = await app.mysql.select('titles', {
            columns: ['id', 'title', 'score', 'type'], // 排除答案
        })
        const allP = titles.map(item => {
            return app.mysql.select('options', {
                where: {title_id:item.id}
            })
        })
        const options = await Promise.all(allP);  // race
        return titles.map((item,ind) => {
            return {
                ...item,
                checks: options[ind]
            }
        })
        
    }
    async submit() {
        const { ctx, app } = this;
        // [{id:1,answer:1}]
        const {answerList} = ctx.request.body;
        let score = 0;
        const data = await Promise.all(answerList.map(item=>{
            return new Promise(async (resolve,reject)=>{
                const res=  await app.mysql.get('titles', {id:item.id, answer:item.answer})
                if(res){
                    resolve(res)
                } else {
                    resolve(item.id*1)
                }
            })
        }))
        return {
            allScore: data.filter(item=> typeof item !== 'number').reduce((prev,next)=>{
                return prev+=next.score
            },0),
            errorTitles: data.filter(item=> typeof item === 'number')
        }
        
    }
}

module.exports = UserService;
